package org.my.workflow.element;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.my.workflow.WorkflowContext;
import org.w3c.dom.Element;

/**
 * @author <a href="mailto:yang_y@sysnet.com.cn">Young Yang</a>
 */
public class StepElement implements ConfigElement {

    private String id;
    private String name;

    // 表示的是进入该 Step 的Condition，再 WorkflowPersistence.nextStep 时进行判断
    // 而一旦该 Step 已经成为 Current Step，则不再判断
    protected List<ConditionElement> conditionElements = new ArrayList<ConditionElement>();

    protected List<InterceptorElement> interceptors = new ArrayList<InterceptorElement>();
    protected List<ActionElement> actionElements = new ArrayList<ActionElement>();

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void processXML(Element element) {
        this.id = XMLUtils.getAtrributeValue(element, "id");
        this.name = XMLUtils.getAtrributeValue(element, "name");

        Element conditionsXMLElement = XMLUtils.getChildElementByTagName(element, "conditions");
        if (conditionsXMLElement != null) {
            List<Element> conditionXMLElements = XMLUtils.getChildElementsByTagName(conditionsXMLElement, "condition");
            for (Element conditionXMLElement : conditionXMLElements) {
                ConditionElement conditionElement = new ConditionElement();
                conditionElement.processXML(conditionXMLElement);
                conditionElements.add(conditionElement);
            }
        }

        Element actionsXMLElement = XMLUtils.getChildElementByTagName(element, "actions");
        List<Element> actionXMLElements = XMLUtils.getChildElementsByTagName(actionsXMLElement, "action");
        for(Element actionXMLElement : actionXMLElements){
            ActionElement actionElement = new ActionElement();
            actionElement.processXML(actionXMLElement);
            actionElement.setStepElementId(getId());
            actionElements.add(actionElement);
        }
    }

    public List<ConditionElement> getConditionElements() {
        return Collections.unmodifiableList(conditionElements);
    }

    public ActionElement[] getActionElements(){
        return actionElements.toArray(new ActionElement[actionElements.size()]);
    }

    public String toString() {
        return super.toString() + "[" + name + "]";
    }

    public boolean checkCondition(WorkflowContext wfContext){
        for (ConditionElement conditionElement : conditionElements) {
            if (!conditionElement.getCondition().isAllowed(wfContext, conditionElement)) {
                return false;
            }
        }
        return true;
    }


/*
    public ResultElement walk(WorkflowContext wfContext) {
        return null;
    }
*/

}
